package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {
    /*
     * 添加到购物车
     *
     * */
    @Autowired
    private ShoppingCartService shoppingCartService;

    @PostMapping("/add")
    public R add(@RequestBody ShoppingCart shoppingCart) {
        //组装条件
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, BaseContext.getId());
        //1.先判断当前加入购物车的菜品/套餐，在当前用户的购物车是否已存在
        //查询条件   user_id  dish_id/setmeal_id
        if (shoppingCart.getDishId() != null) {
            queryWrapper.eq(ShoppingCart::getDishId, shoppingCart.getDishId());
        } else {
            queryWrapper.eq(ShoppingCart::getSetmealId, shoppingCart.getSetmealId());
        }
        ShoppingCart cart = shoppingCartService.getOne(queryWrapper);
        //2.如果不存在，组装数据，直接保存购物对象
        if (cart == null) {
            shoppingCart.setUserId(BaseContext.getId());
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartService.save(shoppingCart);
        } else {
            //3.如果存在，数量number+1
            cart.setNumber(cart.getNumber() + 1);
            shoppingCartService.updateById(cart);
        }
        return R.success(shoppingCart);

    }

    /*
     * 查询用户购物车列表数据
     * */
    @GetMapping("/list")
    public R<List<ShoppingCart>> list() {
        log.info("查询用户购物车列表数据");
        //组装条件
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        //从BaseContext中查询到用户的id
        wrapper.eq(ShoppingCart::getUserId, BaseContext.getId());
        wrapper.orderByDesc(ShoppingCart::getCreateTime);
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(wrapper);
        return R.success(shoppingCartList);
    }


    /*
    *
    * 清空购物车
    * */
    @DeleteMapping("/clean")
    public R clean(){
        log.info("清空当前用户的购物车数据 .... ");

        //组装条件
        LambdaQueryWrapper<ShoppingCart> cartLambdaQueryWrapper = new LambdaQueryWrapper<>();
        cartLambdaQueryWrapper.eq(ShoppingCart::getUserId, BaseContext.getId());

        //执行删除
        shoppingCartService.remove(cartLambdaQueryWrapper);
        return R.success();
    }

}
